package com.maodou.android.ui.page.setting

import android.content.Context
import android.graphics.Bitmap
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.KeyboardArrowLeft
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.qrcode.QRCodeWriter
import com.maodou.android.data.model.ContactInfoVo
import com.maodou.android.ui.page.account.copyText
import com.maodou.android.ui.page.account.pasteText
import com.maodou.android.viewmodel.setting.SettingViewModel
import com.maodou.android.viewmodel.splash.SplashViewModel
import com.maodou.core.navigation.Navigator3
import com.maodou.core.ui.components.ActionBar
import com.maodou.core.ui.components.AppAsyncImage
import com.maodou.core.ui.components.HSpacer
import com.maodou.core.ui.components.TitleAlignment
import com.maodou.core.ui.components.debouncedClickable
import com.maodou.core.ui.components.textfield.AppTextField
import com.maodou.core.ui.components.textfield.MultilineTextField
import com.maodou.core.ui.components.textfield.TextFieldType
import com.maodou.core.ui.components.textfield.TypedTextField
import com.maodou.core.ui.components.textfield.Validators
import java.util.Hashtable

@Composable
fun ContactUsScreen(
    viewModel: SettingViewModel = hiltViewModel()
) {
    val context = LocalContext.current
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    var contact by rememberSaveable { mutableStateOf("") }
    var feedback by rememberSaveable { mutableStateOf("") }

    Column(modifier = Modifier.fillMaxSize()) {
        ActionBar(
            title = "联系我们",
            modifier = Modifier.fillMaxWidth(),
            navigationIcon = Icons.AutoMirrored.Outlined.KeyboardArrowLeft,
            onNavigationClick = { Navigator3.pop() },
            backgroundColor = Color.Transparent,
            contentColor = MaterialTheme.colorScheme.onSurface,
            titleAlignment = TitleAlignment.Center,
        )

        LazyColumn(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f),
            contentPadding = PaddingValues(16.dp)
        ) {

            item {
                TypedTextField(
                    value = contact,
                    onValueChange = { contact = it },
                    type = TextFieldType.Text,
                    label = "联系方式",
                    placeholder = "邮箱/Telegram",
                    borderless = false
                )
                Spacer(modifier = Modifier.height(12.dp))

                MultilineTextField(
                    value = feedback,
                    onValueChange = { feedback = it },
                    label = "反馈内容",
                    placeholder = "请尽量详细描述您的问题或建议…",
                    minLines = 3,
                    maxLines = 5,
                    borderless = false
                )
                Spacer(modifier = Modifier.height(16.dp))

                Button(
                    onClick = { viewModel.submitFeedback(contact,feedback) },
                    enabled = feedback.length >= 10 && !uiState.isLoading,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(48.dp),
                    shape = RoundedCornerShape(8.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary,
                        contentColor = Color.White
                    )
                ) {
                    if (uiState.isLoading) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(16.dp),
                            strokeWidth = 2.dp,
                            color = MaterialTheme.colorScheme.onSecondary
                        )
                        HSpacer(4.dp)
                        Text(text = "提交中...", textAlign = TextAlign.Center, color = MaterialTheme.colorScheme.onSecondary)
                    } else {
                        Icon(imageVector = Icons.Filled.Send, contentDescription = null)
                        Spacer(Modifier.size(8.dp))
                        Text(text = "提交", style = MaterialTheme.typography.titleSmall)
                    }
                }

                Spacer(modifier = Modifier.height(24.dp))
                Text(
                    text = "其他联系方式",
                    style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold)
                )
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "点击可以复制",
                    style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp), color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Spacer(modifier = Modifier.height(12.dp))
            }

            if(uiState.contact?.size != 0) item {
                FlowRow(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    uiState.contact?.forEach { data ->
                        ContactMethodCard(context,data = data)
                    }
                }
                Spacer(modifier = Modifier.height(16.dp))
            }

            item {
                val bottomPadding =
                    WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()
                Spacer(Modifier.height(bottomPadding))
            }
        }
    }
}

@Composable
private fun ContactMethodCard(context: Context, data: ContactInfoVo) {
    Card(
        modifier = Modifier.size(172.dp, 200.dp),
        shape = RoundedCornerShape(12.dp),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(12.dp)
                .debouncedClickable {
                    copyText(context,"${data.subtitle}")
                },
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.SpaceBetween
        ) {

            if (data.imgUrl != null) {
                AppAsyncImage(
                    data.imgUrl,
                    modifier = Modifier.size(144.dp)
                )
            } else {
                val img = rememberQrBitmap(data.link ?: "", 144.dp)
                if (img != null) {
                    Image(bitmap = img, contentDescription = null, modifier = Modifier.size(144.dp))
                } else {
                    Box(
                        modifier = Modifier
                            .size(144.dp)
                            .background(Color(0xFFF2F2F2), RoundedCornerShape(8.dp)),
                        contentAlignment = Alignment.Center
                    ) { Text("QR", color = MaterialTheme.colorScheme.onSurfaceVariant) }
                }
            }

            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "${data.title}",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurface
                )
                data.subtitle?.let {
                    Text(
                        text = it,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                data.subtitle?.let {
                    Text(
                        text = it,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }
    }
}

@Composable
private fun rememberQrBitmap(text: String, size: Dp): ImageBitmap? {
    val density = LocalDensity.current
    val px = with(density) { size.roundToPx() }
    return remember(text, px) { generateQrBitmap(text, px) }
}

private fun generateQrBitmap(text: String, sizePx: Int): ImageBitmap? {
    return try {
        val hints = Hashtable<EncodeHintType, Any>().apply {
            put(EncodeHintType.CHARACTER_SET, "UTF-8")
            put(EncodeHintType.MARGIN, 1)
        }
        val bitMatrix = QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, sizePx, sizePx, hints)
        val bmp = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888)
        for (x in 0 until sizePx) {
            for (y in 0 until sizePx) {
                bmp.setPixel(x, y, if (bitMatrix[x, y]) 0xFF000000.toInt() else 0xFFFFFFFF.toInt())
            }
        }
        bmp.asImageBitmap()
    } catch (e: Exception) {
        null
    }
}